import React, { useState, useEffect, useContext } from "react";
import { useNavigate } from "react-router-dom";
import { Link } from "react-router-dom";
import { AppState } from "../App";
import { ethers } from "ethers";
import { useParams } from "react-router-dom";
import "../css/forus.css";
import "../css/loader.css";

function ForUs() {
  const App = useContext(AppState);
  const { id } = useParams();
  const [Useramount, setUseramount] = useState();
  const [Data, setData] = useState([]);
  const [num, setnum] = useState(0);
  const navigate = useNavigate();
  const image =
    "https://images.pexels.com/photos/464342/pexels-photo-464342.jpeg";
  const [loading, setLoading] = useState(true); 

  const CreateRecord = async () => {
    navigate("/header/creatforus");
  };
  useEffect(() => {
    if (App.Foundationcontract) {
      const getProposals = async () => {
        try {
          const Count = await App.Foundationcontract.userrequestsNumber();

          let proposals = [];
          for (let i = 0; i < Count; i++) {
            const Proposal = await App.Foundationcontract.userrequestions(i);
            console.log(Proposal.photo);
            if (Proposal.completed === false) {
              proposals.push(Proposal);
              console.log(proposals);
            }
          }
          console.log(proposals);
          setData(proposals);
          setLoading(false); 
          console.log(proposals);
        } catch (error) {
          console.log(error);
        }
      };
      getProposals();
    }
  }, [App.Foundationcontract, num]); 

  const Contribute = async (id, Useramount) => {
    try {
      const tx = await App.Foundationcontract.usersendMoney(id, {
        value: Useramount,
      });
      console.log(tx);
      await tx.wait();
      alert("捐赠成功!");
    } catch (error) {
      console.log(error.message);
      alert("捐款必须大于100WEI");
    }
  };
  const itemsPerPage = 3; 
  const [currentPage, setCurrentPage] = useState(1); 
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentItems = Data.slice(indexOfFirstItem, indexOfLastItem);
  const pageNumbers = [];
  for (let i = 1; i <= Math.ceil(Data.length / itemsPerPage); i++) {
    pageNumbers.push(i);
  }
  const handleClick = (pageNumber) => {
    setCurrentPage(pageNumber);
  };
  return (
    <div>
      {loading && <div className="loader"></div>}
      <div
        className="flex flex-col justify-center items-center h-screen"
        style={{
          backgroundImage: `url(${image})`,
          backgroundColor: "rgb(10, 10, 10)",
          backgroundSize: "cover",
          backgroundPosition: "center",
          width: "100%",
          height: "100vh",
        }}
      >
        <div className="oneDiv">
          <div className="content_container">
            <span className="contentFont text-black text-6xl font-bold contentSpan">
              为我们筹款
            </span>
          </div>
          <div
            onClick={CreateRecord}
            className="flex border-opacity-60 bg-opacity-90 text-lg font-medium border-2  cursor-pointer text-black mt-1 rounded-2xl justify-center items-center py-1 px-2 mt-4 connectDiv"
          >
            创建筹款
          </div>
        </div>
      </div>
      <p className="text-center text-black text-3xl font-bold mt-10 mb-10">
        无论是举办生日派对、规划社区项目、参加挑战还是跑马拉松，
        <br />
        您都可以创建个人筹款页面来庆祝——同时与我们脆弱的野生动植
        <br />
        物、栖息地和自然资源分享您的爱心。现在就开始创建您的页面吧！
      </p>
      <div class="grid sm:grid-cols-1 lg:grid-cols-3 gap-4">
        {currentItems.length !== 0 ? (
          currentItems.map((e, id) => {
            return (
              <div class="p-4">
                <div class="h-full bg-gray-100 bg-opacity-75 px-8 pt-16 pb-24 rounded-lg overflow-hidden text-center relative dynamic-background">
                  <h2 class="tracking-widest -ml-5 text-15px title-font font-medium text-gray-900 mb-1">
                    筹款方地址
                  </h2>
                  <h2
                    class="tracking-widest -ml-5 text-base title-font font-medium text-gray-900 mb-1"
                    style={{ fontSize: "11px" }}
                  >
                    {e.recipient}
                  </h2>
                  <h2
                    class="tracking-widest -ml-5 text-base title-font font-medium text-gray-900 mb-1"
                    style={{ fontSize: "20px" }}
                  >
                    {e.tittle}
                  </h2>
                  <Link
                    to={`/header/forus/${e.uniqueid}`}
                    className="image-link"
                  >
                    <img
                      style={{ width: "300px", height: "300px" }}
                      src={`https://blush-chemical-hedgehog-894.mypinata.cloud/ipfs/${e.photo}`}
                      alt="Proposal Photo"
                    />
                  </Link>
                  <h1 class="title-font sm:text-xl text-lg font-medium text-gray-900 mb-3"></h1>
                  <p class="leading-relaxed mt-5 mb-5">{e.description}</p>
                  <div class="text-center mt-2 leading-none flex justify-center absolute bottom-0 left-0 w-full py-4">
                    <span class="text-black  font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                      已收到
                    </span>
                    <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                      {e.userraisedAmount.toString()} WEI { }
                    </span>
                    <span class="text-black ml-10 font-bold mr-3 inline-flex items-center leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                      所需金额
                    </span>
                    <span class="text-black font-bold  inline-flex items-center leading-none text-sm">
                      {Number(e.targetMoney.toString())} WEI { }
                    </span>
                  </div>
                  <div className="flex justify-center absolute bottom-10 left-0 w-full py-4">
                    <input
                      type="text"
                      placeholder="Amount in WEI"
                      className="donateInput"
                      onChange={(e) => setUseramount(e.target.value)}
                    />
                    <button
                      onClick={() =>
                        Contribute(
                          e.uniqueid,
                          ethers.utils.parseUnits(Useramount, 0)
                        )
                      }
                      class="flex mx-auto mt-10 text-white bg-yellow-400 border-0 py-2 px-8 focus:outline-none hover:bg-yellow-600 rounded"
                    >
                      捐赠
                    </button>
                  </div>

                </div>
              </div>
            );
          })
        ) : (
          <div class="flex items-center justify-center nonDIv">
            <div class="title-font sm:text-2xl text-xl font-medium text-gray-900  text-black">
              没有相关内容。
            </div>
          </div>
        )}
      </div>
      {currentItems.length !== 0 && (
        <div className="pagination-container">
          <button
            className={`pagination-button ${currentPage === 1 ? "disabled" : ""}`}
            onClick={() => handleClick(currentPage - 1)}
            disabled={currentPage === 1}
          >
            上一页
          </button>
          {pageNumbers.map((number) => (
            <button
              key={number}
              className={`pagination-button ${currentPage === number ? "active" : ""}`}
              onClick={() => handleClick(number)}
            >
              {number}
            </button>
          ))}
          <button
            className={`pagination-button ${currentPage === pageNumbers.length ? "disabled" : ""}`}
            onClick={() => handleClick(currentPage + 1)}
            disabled={currentPage === pageNumbers.length}
          >
            下一页
          </button>
        </div>
      )}
      <footer className="footer">
        <div className="footer-container">
          <div className="footer-links">
            <div className="link-wrapper">
              <a className="footer-link" href="#">
                About Us
              </a>
              <div className="tooltip">About Us 悬浮窗内容</div>
            </div>
            <div className="link-wrapper">
              <a className="footer-link" href="#">
                Contact Us
              </a>
              <div className="tooltip">
                电话号码:123-456-7890
                <br />
                QQ邮箱号:12345678
              </div>
            </div>
            <div className="link-wrapper">
              <a className="footer-link" href="#">
                Security and Privacy
              </a>
              <div className="tooltip">Security and Privacy 悬浮窗内容</div>
            </div>
          </div>
          <div className="footer-copyright">
            <p>
              &copy; {new Date().getFullYear()} SongWarm. All rights reserved.
            </p>
          </div>
        </div>
      </footer>
    </div>
  );
}

export default ForUs;
